package org.hawksee.javase;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;

import javax.swing.JPanel;

import org.hawksee.core.data.BaseMonochromeImage;
import org.hawksee.core.tools.Manager;

/*
 * This class is the main image panel.
 */
public class StitcherPanel extends JPanel implements MouseListener, MouseMotionListener
{
  public static final long serialVersionUID = 0;
  
  private Manager manager;
  private Point lastPt;
  
  public StitcherPanel(Manager manager)
  {
    this.manager = manager;
    this.addMouseListener(this);
    this.addMouseMotionListener(this);
  }
  /*
   * Draws an image.
   */
  private void drawImage(Graphics g, BufferedMonochromeImage image, Color borderColor)
  {
    g.drawImage(image.getImage(), image.getX(), image.getY(), this);
    if (borderColor != null) {
      g.setColor(borderColor);
      g.drawRect(image.getX(), image.getY(), image.getWidth(), image.getHeight());
    }
  }
  public void mouseClicked(MouseEvent e) { }
  public void mouseMoved(MouseEvent e) {}
  public void mouseDragged(MouseEvent e) 
  {
    if (this.lastPt == null) {
      return;
    }
    Point pt = e.getPoint();
    if (pt.x < 0) pt.x = 0;
    if (pt.y < 0) pt.y = 0;
    if (pt.x >= this.getWidth()) pt.x = this.getWidth();
    if (pt.y >= this.getHeight()) pt.y = this.getHeight();
    this.manager.moveSelected(pt.x - this.lastPt.x, pt.y - this.lastPt.y, false);
    this.lastPt = pt;
    this.repaint();
  } 
  public void mousePressed(MouseEvent e) 
  {
    this.lastPt = e.getPoint();
    this.manager.selectImage(this.lastPt.x, this.lastPt.y);
    this.repaint();
  }
  public void mouseReleased(MouseEvent e) {}
  public void mouseEntered(MouseEvent e) {}
  public void mouseExited(MouseEvent e) {}
  public void paint(Graphics g)
  {
    Rectangle rect = g.getClipBounds();
    g.clearRect(rect.x, rect.y, rect.width, rect.height);
    Color color = null;
    for (BaseMonochromeImage image : this.manager.getImages()) {
      if (this.manager.isSelected(image)) {
        color = Color.RED;
      } else if (this.manager.isTargeted(image)) {
        color = Color.YELLOW;
      } else {
        color = null;
      }
      this.drawImage(g, (BufferedMonochromeImage)image, color);
    }
  }
}
